import string
from typing import List

from fastapi import Depends,FastAPI,HTTPException
from sqlalchemy.orm import Session

import crud, models, schemas
from database import SessionLocal,engine



models.Base.metadata.create_all(bind=engine)

app=FastAPI()

#Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

#add an user
@app.post("/users/add_user",response_model=schemas.User)
def add_user(data:schemas.User,db:Session = Depends(get_db)):
    db_user = crud.add_user(db,user=data)
    if db_user:
        raise HTTPException(status_code=400,detail="Email already registered")
    return crud.add_user(db=db,user=data)

#get users
@app.get("/users/",response_model=List[schemas.User])
def read_users(skip:int = 0,limit: int = 100,db: Session = Depends(get_db)):
    users = crud.get_users(db,skip=skip,limit=limit)
    return users

#get an user
@app.get("/users/{user_id}",response_model=schemas.User)
def read_user(user_id: int,db:Session = Depends(get_db)):
    db_user = crud.get_user(db,user_id=user_id)
    if db_user is None :
        raise HTTPException(status_code=404,detail="User not found")
    return db_user

#新增房间
@app.post("/users/{user_id}/roomInfo/add_room",response_model=schemas.RoomInfo)
def add_user_roomInfo(
    user_id:int,roomInfo:schemas.RoomInfo,db:Session = Depends(get_db)
):
    return crud.add_user_roomInfo(db=db,roomInfo=roomInfo,user_id=user_id)

#获得房间列表
@app.get("/users/{user_id}/roomInfo",response_model=List[schemas.RoomInfo])
def get_user_roomInfo(skip:int = 0,limit:int = 100,db:Session = Depends(get_db)):
    roomInfo = crud.get_user_roomInfo(db,skip=skip,limit=limit)
    return roomInfo

#获得指定房间
@app.get("/users/{user_id}/roomInfo/{rid}",response_model=schemas.RoomInfo)
def get_user_roomInfo_by_rid(user_id:int,rid:int,db:Session=Depends(get_db)):
    roomInfo=crud.get_user_roomInfo_by_rid(db=db,user_id=user_id,rid=rid)
    return roomInfo

#获得用户电话号码
@app('/')
def get_user_phone(data:str):
    print(data)
    return data